﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cqrs.Infrastructure;
using Harmonic.Domain;

namespace Harmonic.ReadModel
{
    public class EventHandlers //: IHandlesEvent<UserCreated>
    {
        public void Handle(UserCreated message)
        {
            using (ReadModel readModel = new ReadModel())
            {                
                readModel.Users.AddObject(new User()
                {
                    Id = message.Id,
                    Password = message.Password,
                    Username = message.Username,
                    State = message.State.Name,
                    Email = message.Email,
                    Version = message.Version
                });
                readModel.SaveChanges();
            }
        }

        public void Handle(UserMadePriority message)
        {
            using (ReadModel readModel = new ReadModel())
            {
                User user = readModel.Users.First(u => u.Id == message.Id);
                user.State = message.State.Name;
                user.Version = message.Version;
                readModel.SaveChanges();
            }
        }

        public void Handle(UserDeleted message)
        {
            using (ReadModel readModel = new ReadModel())
            {
                User user = readModel.Users.First(u => u.Id == message.Id);
                readModel.Users.DeleteObject(user);
                readModel.SaveChanges();
            }
        }

        public void Handle(UserMadeActive message)
        {
            using (ReadModel readModel = new ReadModel())
            {
                User user = readModel.Users.First(u => u.Id == message.Id);
                user.State = message.State.Name;
                user.Version = message.Version;
                readModel.SaveChanges();
            }
        }
    }
}
